﻿using Quartz;

namespace TaskMasterByQuartz.Domain.Helper
{
    public class CreateTriggerHelper
    {
        /// <summary>
        /// 创建类型Simple的触发器
        /// </summary>
        /// <param name="jobName">任务名</param>
        /// <param name="jobGroupName">任务组</param>
        /// <param name="cron"></param>
        /// <param name="beginTime">开始时间</param>
        /// <param name="runTimes">执行次数</param>
        /// <param name="IntervalSecond">间隔时间</param>
        /// <returns></returns>
        public ITrigger CreateSimpleTrigger( string jobName, string jobGroupName, string cron, DateTimeOffset beginTime,int? runTimes, int IntervalSecond)
        {
            //作业触发器
            if (runTimes.HasValue && runTimes > 0)
            {
                return TriggerBuilder.Create()
               .WithIdentity(jobName, jobGroupName)
               .StartAt(beginTime)//开始时间
                                         //.EndAt(entity.EndTime)//结束数据
               .WithSimpleSchedule(x =>
               {
                   x.WithIntervalInSeconds(IntervalSecond)//执行时间间隔，单位秒
                        .WithRepeatCount(runTimes.Value)//执行次数、默认从0开始
                        .WithMisfireHandlingInstructionFireNow();
               })
               .ForJob(jobName, jobGroupName)//作业名称
               .Build();
            }
            else
            {
                return TriggerBuilder.Create()
               .WithIdentity(jobName, jobGroupName)
               .StartAt(beginTime)//开始时间
                                         //.EndAt(entity.EndTime)//结束数据
               .WithSimpleSchedule(x =>
               {
                   x.WithIntervalInSeconds(IntervalSecond)//执行时间间隔，单位秒
                        .RepeatForever()//无限循环
                                        //.WithMisfireHandlingInstructionFireNow();
                        .WithMisfireHandlingInstructionIgnoreMisfires();
               })
               .ForJob(jobName, jobGroupName)//作业名称
               .Build();
            }

        }

        /// <summary>
        /// 创建类型Cron的触发器
        /// </summary>
        /// <param name="jobName">任务名</param>
        /// <param name="jobGroupName">任务组</param>
        /// <param name="cron"></param>
        /// <param name="beginTime">开始时间</param>
        /// <returns></returns>
        public ITrigger CreateCronTrigger(string jobName,string jobGroupName,string cron,DateTimeOffset beginTime)
        {
            // 作业触发器
            return TriggerBuilder.Create()

                   .WithIdentity(jobName, jobGroupName)
                   .StartAt(beginTime)//开始时间
                   //.EndAt(entity.EndTime)//结束时间
                   .WithCronSchedule(cron, cronScheduleBuilder => cronScheduleBuilder.WithMisfireHandlingInstructionDoNothing())//指定cron表达式  WithMisfireHandlingInstructionFireAndProceed
                   .ForJob(jobName, jobGroupName)//作业名称
                   .Build();
        }
    }
}
